from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
from user.models import *
from room.models import *
from contract.models import *
from order.models import *


@csrf_exempt
def rent(request):
    if request.method == 'POST':
        data_json = json.loads(request.body)
        username = request.session.get('username', "")
        if username == "":
            return JsonResponse({'errno': 1002, 'msg': "请先登录"})
        else:
            rid = data_json.get('rid', 0)
            rent_type = data_json.get('rent', 0)
            period = data_json.get('period', 0)
            user = User.objects.get(username=username)
            room = Room.objects.get(id=rid)
            order = Order(uid=user.id, rid=room.id, rent=rent_type, period=period)
            if rent_type == 2:
                contract = Contract(uid=user.id, rid=room.id, period=period)
                contract.save()
                order.cid = contract.id
                order.save()
            room.uid = user.id
            room.status = rent_type
            room.save()
    else:
        return JsonResponse({'errno': 1001, 'msg': "请求方式错误"})

